<?php
namespace App\Controllers;

use Framework\Database;
use Framework\Validation;
use Framework\Session;

class UserController{
    protected $db;

    public function __construct(){
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }
    public function login(){
        //调用loadView函数来加载登录页面的视图
        loadView('users/login');
    }

    public function create(){
        loadView('users/create');
    }

    public function store(){
        //从P0ST请求中获取用户数据
        $name = $_POST['name'];
        $email = $_POST['email'];
        $city = $_POST['city'];
        $province = $_POST['province'];
        $password = $_POST['password'];
        $passwordConfirmation = $_POST['password_confirmation'];
        //初始化一个数组来存放可能的错误信息
        $errors = [];
        //验证电子邮件是否有效
        if (!Validation::email($email)){
            $errors['email']='请输入一个合法的电子邮箱地址!';
        }
        //验证名字是否在2到58字符之间
        if (!Validation::string($name,2,50)){
            $errors['name']='姓名长度为2到50!';
        }
        //验证密码长度至少为6宇符
        if (!Validation::string($password,6,50)){
            $errors['password']='密码长度为至少6位!';
        }
        //验证密码和确认密码是否匹配
        if (!Validation::match($password,$passwordConfirmation)){
            $errors['password_confirmation']='两次的输入密码不一致！';
        }
        // 检查是否存在验证错误
        if (!empty($errors)){
            // 如果存在错误，重新加载注册页面并显示错误信息
            loadView('users/create',[
                'errors'=>$errors,
                'user' =>[
                    'name'=>$name,
                    'email'=>$email,
                    'city'=>$city,
                    'province'=>$province,
                ]
            ]);
            exit;
        }
        else{
            $params = [
                'email' => $email
            ];

            $user = $this->db->query('SELECT * FROM users WHERE email = :email',$params)->fetch();

            // 如果查询要用户
            if ($user){
                $errors['email'] = '该邮箱已被注册!';
                loadView('user/create',[
                    'errors'=>$errors
                ]);
                exit;
            }

            // 创建用户账户
            $params =[
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
                'password' => password_hash($password,PASSWORD_DEFAULT)
            ];

            // 执行SQL插入操作，将心用户数据插入数据库
            $this->db->query('INSERT INTO users (name,email,city,province,password) VALUES (:name,:email,:city,:province,:password)',$params);

            // Get new user ID
            $userId = $this->db->conn->lastInsertId();

            Session::set('user',[
                'id' => $userId,
                'name' => $name,
                'email' => $city,
                'province' => $province
            ]);
            // 创建用户成功后重定向到首页
            redirect('/');
        }
        
    }
    /**
     * 注销用户并结束对话
     * 
     * @return void
     */
    public static function logout(){
        Session::clearAll();

        $params = session_get_cookie_params();

        setcookie('PHPSESSID','',time() - 86400, $params['path'],$params['domain']);

        redirect('/');

    }

    /**
     * 使用电子邮件和密码验证用户身份
     * 
     * @return void
     */
    public function authenticate(){
        $email = $_POST['email'];
        $password = $_POST['password'];

        // 初始化错误数组
        $errors = [];

        // 验证电子邮件的格式
        if (!Validation::email($email)) {
            $errors['email'] = '请输入合法的邮箱地址！';
        }

        // 验证密码长度（至少6个字符，最多50个字符）
        if (!Validation::string($password,6,50)) {
            $errors['password'] = '密码至少为6位！';
        }

        //如果存在验证错误，重新加载登录页面并显示错误
        if (!empty($errors)) {
            loadView('users/login',[
                'errors'=>$errors
            ]);
        }

        // 准备查询参数，查找电子邮件
        $params = [
            'email' => $email
        ];

        // 从数据库查询用户
        $user = $this->db->query('SELECT * FROM users WHERE email = :email',$params)->fetch();

        // 如果未找到用户，说明电子邮件不正确
        if (!$user){
            $errors['email'] = '用户不存在或密码错误！';
            loadView('users/login',[
                'errors'=>$errors
            ]);
            exit;
        }

        // 验证密码是否正确
        if (!password_verify($password,$user->password)){
            $errors['password'] = '用户不存在或密码错误！';
            loadView('users/login',[
                'errors'=>$errors
            ]);
            exit;
        }

        // 验证通过,设置用户会话信息
        Session::set('user',[
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'city' => $user->city,
            'province' => $user->province
        ]);

        redirect('/');
    }
}






